﻿using System.Data;
using System.Reflection;
using T.FAS.Runtime.MF.Entity.ElsaEntity;
using T.ServiceComponent.DAC.Service;

namespace T.FAS.Runtime.MF.Dao.Dao
{
    public class ActivityExecutionRecordDao : DaoService<ActivityExecutionRecord>
    {
        public override string TableName => "ActivityExecutionRecords";
        public override string IDColumnName => "Id";
        public override string DBName => "TFASMF";

        public List<ActivityExecutionRecord> GetActivityRecordByInstanceId(string instanceId)
        {
            var records = new List<ActivityExecutionRecord>();  
            string sql = @$"SELECT ""Id"", ""WorkflowInstanceId"", ""ActivityId"", ""ActivityNodeId"", 
                            ""ActivityType"", ""ActivityTypeVersion"", ""ActivityName"", ""StartedAt"", 
                            ""HasBookmarks"", ""Status"",
                            ""CompletedAt"", ""SerializedActivityState"", ""SerializedException"", 
                            ""SerializedOutputs"", 
                            ""SerializedPayload"", ""SerializedActivityStateCompressionAlgorithm"",
                               ""SerializedProperties"",
                            ""TenantId""
                            FROM ""Elsa"".""ActivityExecutionRecords"" Where ""WorkflowInstanceId""='{instanceId}'";

            var dataSet = this.DB.ExecuteDataSet(sql);

            if (dataSet != null && dataSet.Tables.Count > 0)
            {
                foreach (DataRow dataRow  in dataSet.Tables[0].Rows)
                {
                    var record = ConvertToObject(base.Columns, dataRow);
                    record.StartedAt = record.StartedAt.AddHours(8);
                    if (record.CompletedAt.HasValue)
                    {
                        record.CompletedAt = record.CompletedAt.Value.AddHours(8);
                    }
                    records.Add(record);
                }
            }
            return records;
        }
        public override ActivityExecutionRecord ConvertToObject(Dictionary<string, PropertyInfo> columns, DataRow row)
        {
            var myCol = new Dictionary<string, PropertyInfo>(base.Columns);

            var data = base.ConvertToObject(myCol, row);

            return data;
        }
    }
}

